import { api_shop_seller, api_goods_goods_list } from "@/apis/shop"

// 店铺数据
const state = {
    shopData: {},
    tabsLength: 0,
    goodsList: []

}

const getters = {
    goodsName(state) {
        return state.goodsList.map(v => v.name)
    },
    filterFoodsData(state) {
        let temp = []
        state.goodsList.forEach(v => {
            v.foods.forEach(item => {
                if (item.acount > 0) {
                    temp.push(item)
                }
            })
        })
        return temp
    },
    // 总计价钱
    reduceTotal(state, getters) {
        return getters.filterFoodsData.reduce((total, cur) => {
            return total + cur.price * cur.acount
        }, 0)
    },

    // 总计数量
    reduceAcount(state, getters) {
        return getters.filterFoodsData.reduce((total, cur) => {
            return total + cur.acount
        }, 0)
    }

}

const mutations = {
    GET_SHOP_DATA(state, data) {
        state.shopData = data
        state.tabsLength = data.supports.length
    },
    GET_GOODS_LIST(state, data) {
        state.goodsList = data
        state.goodsList.map(v => {
            return v.foods = v.foods.map(item => {
                return item = {
                    ...item,
                    acount: 0
                }
            })
        })
    },
    ADD_ACOUNT(state, id) {
        state.goodsList.map(v => {
            v.foods.map(item => {
                if (item.id == id) {
                    item.acount++
                }
            })
        })

    },
    REDUCE_ACOUNT(state, id) {

        state.goodsList.map(v => {
            v.foods.map(item => {
                if (item.id == id) {
                    item.acount--
                }
            })
        })

    }
}
const actions = {
    // 获取商铺数据
    getShopData({ commit }) {
        return new Promise(async resolve => {
            const res = await api_shop_seller()
            commit('GET_SHOP_DATA', res.data.data)
            resolve()
        })
    },
    // 获取商品数据
    getGoodsData({ commit }) {
        return new Promise(async resolve => {
            const res = await api_goods_goods_list()
            let { code, data } = res.data
            if (code == 0) {
                commit('GET_GOODS_LIST', data)
                resolve()
            }

        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}